///<reference path="../creator.d.ts"/>
namespace QM{
  

    /** 位置 */
    export enum QPoint{
        /** 下 */
        Bottom=1,
        /** 右 */
        Right,
        /** 左 */
        Left
    }


    export type Card={
        name:string;
        color?:string;
        title:string;
    }


    export var CName=["Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King","One","Two","SJoker","LJoker"];
    export var CColor=["Spade","Heart","Club","Square"];

   

    export type QEvent={
        type:string;
        cmd?:string;
        data?:any;     
    }

    export class Socket{     
        public static readonly Instance:Socket = new Socket();
        private readonly dial:string="ws://182.61.37.167:9501";        
        private websocket:WebSocket=null;
        private interval:number=0;
        private events:{target:any,func:Function}[] = []
        constructor(){           
            if(Socket.Instance){
                return Socket.Instance;
            }
        }
        on(func:Function,target?:any){                      
            this.events.push({target:target,func:func});            
        }
        off(func:Function,target?:any){
            this.events.forEach((item,key)=>{
                if(item.func==func && item.target==target){
                    this.events.splice(key,1);
                }
            })            
        }
        connect(){
            if(this.websocket && this.websocket.readyState==WebSocket.OPEN){
                return;
            }
            this.websocket = new WebSocket(this.dial);
                
            this.websocket.onclose = (ev:CloseEvent)=>{
                this.onClose(ev);
            }
            this.websocket.onerror = (ev:Event)=>{
                this.onError(ev);
            }
            this.websocket.onopen = (ev:Event)=>{
                this.onOpen(ev);
            }
            this.websocket.onmessage = (ev:MessageEvent)=>{
                this.onMessage(ev);
            }
            this.interval = setInterval(()=>{
                this.frame();
            },30*1000);                                        
        }
        frame(){
            if(this.websocket && this.websocket.readyState === WebSocket.OPEN){
                this.websocket.send("");
            }
        }
        Send(data:string|object){
            if (this.websocket.readyState === WebSocket.OPEN) {
                if(typeof data=="object"){
                    data = JSON.stringify(data);
                }
                this.websocket.send(data);
            }else{
                console.log("WebSocket 连接错误");
            }            
        }
        onOpen(ev:Event){
            console.log("连接打开");                              
            this.bubbleUp(ev);                              
        }
        onMessage(ev:MessageEvent){                 
            if(ev.data){
                var sd = JSON.parse(ev.data);
                let e:QEvent={
                    type:ev.type,
                    cmd:sd.cmd,
                    data:sd.data                    
                };                
                this.bubbleUp(e);                                  
            }
        }
        onClose(ev:CloseEvent){
            clearInterval(this.interval);
            console.log("连接被关闭");
            //cc.director.loadScene("hall"); 
            //this.bubbleUp(ev);
        }
        onError(ev:Event){
            clearInterval(this.interval);
            console.log("连接错误");
            //this.bubbleUp(ev);
        }
        bubbleUp(ev:QEvent){
            this.events.forEach((item)=>{               
                item.func.call(item.target,ev);
            }) 
        }
    }

   
    export type Character = {
        uid:number;
        username:string;
        point:QPoint;
        fd:number;
    }

  
    

    
    
    /**
     * 房间管理
     */
    export class Room{
        public static readonly Instance:Room=new Room();
        private _roomId:number=0;
        private _landLord:number=0;
        characters:Character[] = [];
        constructor(){            
            if(Room.Instance){
                return Room.Instance;
            }
        }    
        set roomId(rid:number){
            if(!this._roomId){
                this._roomId = rid;
            }else{
                console.log("出错,房间号已设置");
            }            
        }
        get roomId(){
            return this._roomId;
        }

        set landLord(uid:number){
            this._landLord = uid;
        }
        get landLord(){
            return this._landLord;
        }


        addCharacter(ch:Character){         
            if(this.length>=3){
                console.log("房间已满,无法加入")
                return false;
            }           
            if(this.in_Character(ch)){              
                return ;
            }            
            if(ch.uid==QM.User.uid){
                ch.point = QPoint.Bottom;
            }else{
                if(!this.getCharacterForPoint(QPoint.Left)){
                    ch.point = QPoint.Left;
                }else if(!this.getCharacterForPoint(QPoint.Right)){
                    ch.point = QPoint.Right;
                }
            }            
            this.characters.push(ch);
        }
        getCharacterForPoint(point:QPoint){       
            for(var i=0;i<this.characters.length;i++){
                if(this.characters[i].point==point){
                    return this.characters[i];
                }
            }
            return null;
        }
        getCharacterForUid(uid:number){
            for(var i=0;i<this.characters.length;i++){
                if(this.characters[i].uid==uid){
                    return this.characters[i];
                }
            }
            return null;
        }
        in_Character(ch:Character){            
            for(var i=0;i<this.length;i++){
                if(this.characters[i].uid==ch.uid){
                    return true;
                }
            }
            return false;
        }        
        removeCharacter(ch:Character){            
            for(var i=0;i<this.length;i++){
                if(this.characters[i].uid==ch.uid){                    
                    return this.characters.splice(i,1)[0];                    
                }
            }                        
            return null;
        }

        getCharacters(){
            return this.characters;
        }
        
        clear(){
            this.roomId=0;
            this.landLord = 0;
            this.characters = [];            
        }
        get length(){
            return this.characters.length;
        }
    }


    export var User:Character;


    export class JSManager{
        static readonly instance = new JSManager();
        objs:{[key:string]:any}={};
        setClass<T>(fun:Function,obj:T){
          
            var key:string = fun["name"];
            this.objs[key] = obj;

        }
        getClass<T>(fun:Function):T{            
            var key:string = fun["name"];
            return this.objs[key];
        }
    }

}


window.QM = QM;


